import { receiveAddrList, addOrModAddr, deleteAddr, setDefaultAddr, getDefaultAddr, getWarehouseId } from '../../../service/get-data'
import { ALLADDRLIST, DEFAULTADDR } from './mutations-types'
import { setStore } from '@/config/mUntils'
import { eventBus } from '../../../tool/events-bus'
import { setToken } from '@/service/get-data'
export default{
  // 获取分仓id
  async fetchWarehouseId ({rootState}, sendCode = false) {
    let [warehouseId, username, IPCode] = ['', rootState.user.username, rootState.IPCode]
    IPCode = sendCode ? IPCode : undefined
    let res = await getWarehouseId(username, IPCode)
    if (res.data.resultCode && res.data.resultCode === 2000) {
      warehouseId = res.data.data
      setStore('warehouseId', warehouseId)
      setToken()
      return +res.data.data
    }
  },
  // 获取所有的地址
  async fetchAllAddrList ({commit}) {
    let res = await receiveAddrList()
    if (res.data.resultCode && res.data.resultCode === 2000) {
      res = res.data
      commit(ALLADDRLIST, res.data)
      return res.data
    }
  },
  // 添加修改收货地址
  async fetchAddOrModArr ({dispatch, commit}, addrParams) {
    let res = await addOrModAddr(addrParams.name, addrParams.mobile, addrParams.id, addrParams.address, addrParams.province, addrParams.provinceCode, addrParams.city, addrParams.cityCode, addrParams.area, addrParams.areaCode, addrParams.postcode, addrParams.cardNumber)
    if (res.data.resultCode && res.data.resultCode === 2000) {
      // await dispatch('fetchWarehouseId')
      await dispatch('fetchAllAddrList')
    }
  },
  // 删除收货地址
  fetchDeleteAddr ({dispatch, commit}, addrId) {
    eventBus.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteAddr(addrId).then((resolved, reject) => {
        let res = resolved
        if (res.data.resultCode === 2000) {
          // dispatch('fetchWarehouseId').then(res => {
          //   console.log(`返回值${res}`)
          //   if (!res) {
          //     dispatch('fetchWarehouseId', true)
          //   }
          // })
          dispatch('fetchAllAddrList')
        }
      })
    }).catch(() => {
      eventBus.$message({
        type: 'info',
        message: '已取消删除'
      })
    })
  },
  // 设置默认地址
  async fetchSetDefaultAddr ({dispatch, commit}, obj) {
    let res = await setDefaultAddr(obj.addrId)
    if (res.data.resultCode && res.data.resultCode === 2000) {
      // await dispatch('fetchWarehouseId')
      await dispatch('fetchAllAddrList')
    }
  },
  // 获取默认地址
  async fetchGetDefaultAddr ({commit}) {
    let res = await getDefaultAddr()
    if (res.data.resultCode && res.data.resultCode === 2000) {
      commit(DEFAULTADDR, res.data.data)
      return res
    }
  }
}
